package org.jinyan.db.dao.impl;

import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jinyan.admin.model.MyUser;
import org.jinyan.db.dao.IDBDao;
import org.jinyan.db.utils.BeanMapConverUtils;
import org.jinyan.led.model.DeviceInstance;

import com.google.gson.reflect.TypeToken;

public class UserDBMapDao {

	private IDBDao dbDao = new DBDao();

	public boolean add(MyUser user) throws SQLException {
		String addSql = "INSERT INTO user (useruuid,username,password,email) VALUES (?,?,?,?)";
		List parms = new ArrayList();
		parms.add(user.getUseruuid());
		parms.add(user.getUsername());
		parms.add(user.getPassword());
		parms.add(user.getEmail());

		if (user.getUsertype() != null) {
			addSql = "INSERT INTO user (useruuid,username,password,email,usertype) VALUES (?,?,?,?,?)";
			parms.add(user.getUsertype());
		}
		return dbDao.add(addSql, parms.toArray());
	}

	public boolean deleteById(String id) throws SQLException {
		// TODO Auto-generated method stub
		return dbDao.delete("delete from user where useruuid=?", new Object[]{id});
	}

	public boolean update(MyUser model) {
		// TODO Auto-generated method stub
		return false;
	}

	public MyUser select(MyUser user) throws SQLException {
		MyUser resultUser = null;
		String sql = "select * from user t where t.useruuid=? and t.password=?";
		List parms = new ArrayList();
		System.out.println("UserDBMapDao  用户登录SQL " + sql);
		parms.add(user.getUseruuid());
		parms.add(user.getPassword());
		List list = dbDao.selectList(sql, parms.toArray());
		if (list != null && list.size() > 0) {
			Map map = (Map) list.get(0);
			if (map != null) {
				Type type = new TypeToken<MyUser>() {
				}.getType();
				resultUser = (MyUser) BeanMapConverUtils.mapToBean(map, type);
			}

		}
		return resultUser;
	}

	public List<MyUser> listUsers() throws SQLException {
		List<MyUser> resultUsers = null;
		String sql = "select * from user ";

		List list = dbDao.selectList(sql);
		Type type = new TypeToken<List<MyUser>>() {
		}.getType();
		resultUsers = (List<MyUser>) BeanMapConverUtils.mapToBean(list, type);

		return resultUsers;
	}

}
